package com.md.infrastructure.configuration;


import com.google.common.collect.Maps;
import com.md.domain.model.bo.LoginExtraBO;
import com.md.domain.model.po.LoginMethod;
import com.md.exception.ServerException;
import com.md.infrastructure.config.AzureSamlConfig;
import com.md.repository.LoginMethodRepository;
import com.md.util.StringUtil;
import com.md.value.enums.LoginEnum;
import lombok.RequiredArgsConstructor;
import org.opensaml.core.config.InitializationException;
import org.opensaml.core.config.InitializationService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.md.value.enums.LoginEnum.AZURE_SAML;

/**
 * @author 刘骄阳
 * 2024-03-24 1:47
 */
@Component
@RequiredArgsConstructor
public class AfterRunner {
  private final LoginMethodRepository loginMethodRepository;

  @PostConstruct
  public void initConfig() {
    try {
      // 初始化链接
      InitializationService.initialize();
      List<LoginMethod> loginMethods = loginMethodRepository.selectList(new LoginMethod());
      Map<LoginEnum, Map<String, AzureSamlConfig>> map = Maps.newHashMap();
      loginMethods.forEach(loginMethod -> {
        switch (LoginEnum.of(loginMethod.getType())) {
          case AZURE_SAML:
            LoginExtraBO extraBO = StringUtil.jsonToObject(loginMethod.getExtra(), LoginExtraBO.class);
            Optional.ofNullable(extraBO.getAzureSaml()).ifPresent(azureSamlBO -> {
              AzureSamlConfig analysis = AzureSamlCoreConfiguration.analysis(azureSamlBO.getMetadataUrl()).get(0);
              analysis.setEntityId(azureSamlBO.getEntityId());
              map.getOrDefault(AZURE_SAML, Maps.newHashMap()).put(loginMethod.getCode(), analysis);
            });
            break;
          default:
            break;
        }
      });

    } catch (InitializationException e) {
      throw ServerException.build(ErrorEnum.LOGIN_INIT_SAML_CORE_ERROR, e);
    }
  }
}
